import subprocess
from datetime import datetime
from pathlib import Path


import pytest
from Tools.scripts.fixdiv import report

from django.contrib import admin
from django.utils import html

from case.models import API_TEST

import os



# Register your models here


@admin.register(API_TEST)
class TaskAdmin(admin.ModelAdmin):
    list_display = ("id","name","status","report_url")

    def save_model(self, request, obj, form, change):
        super().save_model(request,obj,form,change)

        # 获取测试用例的父目录
        test_dir = Path(str(obj.path))
        if os.path.exists(test_dir) and os.path.isfile(test_dir):
            print(f"文件 {test_dir} 存在")
        else:
            print(f"文件 {test_dir} 不存在")

        # 如果状态为 1，则执行 sanmu run 命令
        if obj.status == 1:
            pytest.main(["E:\\pycharm\\DjangoProject\\pytest_api\\testcase", "--tb=long", "-n=2"])
            obj.status = 2
            report_name = f"{obj.name}"
            report_path = os.path.join("test_report", report_name)
            os.system(f"allure generate -o {report_path} -c temps --language zh-cn")
            obj.status = 3  # 修改状态：执行完毕
            obj.save()

    @admin.display(description="测试报告")
    def report_url(self,obj  ):
        if obj.status == 3:
            report_address = f"test_report\\{obj.name}\\index.html"
            return html.format_html(
                f"<a href='/{report_address}' target='_blank'>点击查看测试报告1</a>"
            )
        else:
            return "-"
